package cd

import (
	"time"
)

// cd: restore cd
// max: restore max
func NewCD(cd time.Duration, max int32) *CD {

	if cd < time.Second {
		panic("cd must > time.Second")
	}

	return &CD{cd: cd, max: int(max), time: time.Now()}
}

type CD struct {
	max  int           // num
	cd   time.Duration // restore cd
	time time.Time
}

func (c *CD) GetNum() (num, sec int32) {

	var n, cd = c.getNum()

	return int32(n), int32(cd / time.Second)
}

func (c *CD) SetNum(n int32) time.Time {

	var _, d = c.getNum()
	if d == 0 {
		d = c.cd
	}

	c.time = time.Now().Add(d - c.cd - c.cd*time.Duration(n))
	return c.time
}

func (c *CD) SetTime(time time.Time) *CD {

	c.time = time
	return c
}

func (c *CD) getNum() (int, time.Duration) {

	var d = time.Now().Sub(c.time)

	var n = int(d / c.cd)
	var cd = c.cd - d%c.cd

	if n >= c.max {
		n = c.max
		cd = 0
	}

	return n, cd
}
